from QQLoginTool.QQtool import OAuthQQ
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from oauths.models import QQLoginUserModel
from oauths.utils import check_save_secret_openid
from users.models import User


class OAuthQQUserSerializer(serializers.Serializer):
    access_token = serializers.CharField(write_only=True, label="登陆凭证")
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(max_length=12, label="密码")
    sms_code = serializers.CharField(write_only=True, max_length=10, label="短信验证码")

    class Meta:
        model = User
        fields = ('mobile', 'password', 'sms_code', 'access_token', 'id', 'username', 'token')
        extra_kwargs = {
            'username': {
                'read_only': True
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate(self, attrs):
        # 校验access_token
        access_token = attrs["access_token"]

        openid = check_save_secret_openid(access_token)

        if not openid:
            raise serializers.ValidationError("无效的openid")
        attrs["openid"] = openid

        # 校验短信验证码
        mobile = attrs["mobile"]
        sms_code = attrs["sms_code"]

        # 从数据库中获取短信验证码

        redis = get_redis_connection("verify")
        try:
            real_redis = redis.get("sms_%s" % mobile)

            real_redis = real_redis.decode()
        except Exception:
            raise serializers.ValidationError("获取短信验证码失败")
        if sms_code != real_redis:
            raise serializers.ValidationError("短信验证码不正确")

        # 校验密码
        # 1　通过手机号码获取用户数据
        try:
            user = User.objects.get(mobile=mobile)

        except User.DoesNotExist:
            pass

        else:
            password = attrs['password']
            if not user.check_password(password):
                raise serializers.ValidationError('密码错误')
            attrs['user'] = user

        return attrs

    def create(self, validated_data):
        mobile = validated_data["mobile"]
        password = validated_data["password"]

        openid = validated_data["openid"]
        try:
            user = validated_data["user"]
        except Exception:
            user = None
        if not user:
            user = User.objects.create(mobile=mobile, password=password, username=mobile)

        QQLoginUserModel.objects.create(openid=openid, user=user)
        user.set_password(password)
        user.save()

        return user